<template>
  <form-model
    ref="makeModal"
    class="makePackageStyle"
    :formTitle="recordData.versionType==='TEST'?'在线差分版本选择 【测试版】':'在线差分版本选择 【定版】'"
    :width="1100"
    :form="form"
    :rules="rules"
    :bodyStyle="{ height: '500px', overflowY: 'auto' }"
    @ok="handleOk"
  >

    <a-form-model-item :class="targetEntirePackageCheck ? '' : 'has-error'">
      <template v-slot:label>
        <span>{{ $t('targetVersion') }}</span>
        <!-- <question-mark-tip
          tip-title="制作差分包需选定一个目标版本"
          :popupContainer="$commonFun.getPopupContainer"
        ></question-mark-tip> -->
      </template>
      <!-- <template v-if="targetVersion">
        <a-row>
          <a-col :span="6">
            <table-ellipsis :text="recordData.name || '--'" :tableEllipsisIsTurnLine="false" style="max-width:80%" :widthContent="80"/>
          </a-col>
          <a-col :span="18">
            <table-ellipsis :text="targetVersion.name || '--'" :tableEllipsisIsTurnLine="false" style="float: left;width:auto;margin-right:20px;max-width:80%" :widthContent="80"/>
            <auth-text :auth="softwarePerms.partsSoftware.delete"
                       @click="deleteEntirePackage(targetVersion.resourceId,() => {targetVersion=null;$emit('refreshVersion')})">
              <a-tooltip :title="$t('delete')"><a-icon type="close"/></a-tooltip>
            </auth-text>
          </a-col>
        </a-row>
      </template> -->
      <!-- <template v-else>
        {{ recordData.name }}
        <auth-text :auth="softwarePerms.partsSoftware.edit" v-if="recordData.versionType === 'TEST'">
          <a-button style="margin-left: 100px" @click="uploadEntirePackage(recordData)">上传全包</a-button>
        </auth-text>
      </template> -->
      <!-- <span style="padding-left:100px;" v-if="!targetEntirePackageCheck">请上传全包</span> -->
    </a-form-model-item>
    <s-table
      style="min-height: 100px;"
      ref="targetTable"
      :rowKey="(record,index)=>index"
      :columns="TargetVersionColums"
      :data-source="TargetVersionLists"
      :loading="loadingTbData"
      :showPagination="false"
      :scroll="{x:2000,y:1000}"
      class="h100"
    ></s-table>
    <a-row :gutter="[16,0]">
      <a-col :md="6" :sm="24">
        <a-form-model-item :label="$t('DLL文件类名')" prop="dllName">
          <a-select
            v-model="form.dllName"
            showSearch
            allow-clear
            :placeholder="$t('默认同目标版本DLL文件类名')"
            optionFilterProp="children"
            :filterOption="$commonFun.filterOption"
            style="width: 100%"
          >
            <a-select-option
              v-for="(item,index) in dllClassNameDictCode"
              :key="index"
              :value="item.value"
              :title="item.name"
            >{{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
      <a-col :md="6" :sm="24">
        <a-form-model-item :label="$t('预计安装时间(s)')" prop="installTime">
          <a-input
            v-model="form.installTime"
            :placeholder="$t('pleaseInput') + $t('预计安装时间')"
            :allow-clear="true" />
        </a-form-model-item>
      </a-col>
      <a-col :md="6" :sm="24">
        <a-form-model-item :label="$t('超时时长(s)')" prop="overTime">
          <a-input
            v-model="form.overTime"
            :placeholder="$t('pleaseInput') + $t('超时时长')"
            :allow-clear="true" />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row class="ant-form-item">
      <div class="ant-form-item-label">
        <label class="ant-form-item-required">
          <span>{{ $t('originalVersion') }}</span>
          <question-mark-tip
            :tip-title="$t('zxzzsourceTip')"
            :popupContainer="$commonFun.getPopupContainer"
          ></question-mark-tip>
        </label>
        <a-button type="text" style="margin-left: 20px" @click="$refs.createEcuModal.add()" title="创建ECU版本">
          <i class="iconfont icon-xinjian" style="margin-right:0">创建ECU版本</i>
        </a-button>
      </div>
    </a-row>
    <!-- 原始版本列表 -->
    <div class="commonTableSty">
      <s-table
        style="min-height: 250px;"
        class="h100"
        ref="table"
        :columns="RawVersionColums"
        :data="loadData"
        :scrollX="900"
        :row-selection="{ selectedRowKeys:selectedRowKeys, onChange: onTableSelectChange, getCheckboxProps: onGetCheckboxProps }"
        rowKey="resourceId"
        size="default" >
        <template slot="resourceName" slot-scope="text, record">
          <template v-if="record.resourceName">
            <table-ellipsis :text="record.resourceName" :tableEllipsisIsTurnLine="false" style="float: left;width:auto;margin-right:20px;max-width:80%" :widthContent="80"/>
            <auth-text
              :auth="softwarePerms.partsSoftware.delete"
              v-if="record.versionPhase === 'TEST'"
              @click="deleteEntirePackage(record.resourceId, ()=>{
                record.resourceId='';
                record.resourceName='';
                record.checked = false;
                refreshData()
              })">
              <a-tooltip :title="$t('delete')"><a-icon type="close"/></a-tooltip>
            </auth-text>
            <!--            <a-button type="link" title="删除" @click="deleteEntirePackage(sourceVersion.resourceId)" v-if="sourceVersion.resourceName">X</a-button>-->
          </template>
          <template v-else>
            <auth-text :auth="softwarePerms.partsSoftware.edit" v-if="record.versionPhase === 'TEST'">
              <a-button style="margin-left: 60px" size="small" @click="uploadEntirePackage(record)">
                上传全包
              </a-button>
            </auth-text>
          </template>
        </template>
      </s-table>
    </div>
    <!-- <template v-for="sourceVersion in sourceVersionList"> -->
      <!-- <a-row style="line-height:50px"> -->
        <!-- <a-col :span="6">
          <table-ellipsis :text="sourceVersion.sourceVersionName+ '【' + ($store.getters.getDictCodeObj('versionTypeDictCode')[sourceVersion.versionPhase] || '')
              + '】'" :tableEllipsisIsTurnLine="false" :widthContent="80"/> -->
<!--          {{ sourceVersion.sourceVersionName }}-->
        <!-- </a-col> -->
        <!-- <a-col :span="9"> -->
          <!-- <template v-if="sourceVersion.resourceName"> -->
            <!-- <table-ellipsis :text="sourceVersion.resourceName" :tableEllipsisIsTurnLine="false" style="float: left;width:auto;margin-right:20px;max-width:80%" :widthContent="80"/> -->
            <!-- <auth-text :auth="softwarePerms.partsSoftware.delete"
                       v-if="sourceVersion.versionPhase === 'TEST'"
                       @click="deleteEntirePackage(sourceVersion.resourceId, ()=>{
                         sourceVersion.resourceId='';
                         sourceVersion.resourceName='';
                         sourceVersion.checked = false;
                       })">
              <a-tooltip :title="$t('delete')"><a-icon type="close"/></a-tooltip>
            </auth-text> -->
            <!--            <a-button type="link" title="删除" @click="deleteEntirePackage(sourceVersion.resourceId)" v-if="sourceVersion.resourceName">X</a-button>-->
          <!-- </template> -->
          <!-- <template v-else>
            <auth-text :auth="softwarePerms.partsSoftware.edit" v-if="sourceVersion.versionPhase === 'TEST'">
              <a-button style="margin-left: 100px" @click="uploadEntirePackage(sourceVersion)">
                上传全包
              </a-button>
            </auth-text>
          </template> -->
        <!-- </a-col> -->
        <!-- <a-col :span="2">
          <a-checkbox v-model="sourceVersion.checked" style="padding-right: 10px"
                      :disabled="!sourceVersion.resourceName"/>
        </a-col> -->
        <!-- <a-col :span="7"> -->
          <!-- <div style="
              display: block;
              line-height: 50px;
              float: left;
              font-size: 30px;
              margin-top: -3px;
              color: deepskyblue;">
            ↑
          </div> -->
          <!-- <div style="padding: 10px 5px 0 0 ;">
            <table-ellipsis :text="recordData.name" :tableEllipsisIsTurnLine="false" style="line-height: 15px;width:auto;max-width:80%" :widthContent="80"/>
            <table-ellipsis :text="sourceVersion.sourceVersionName" :tableEllipsisIsTurnLine="false" style="line-height: 15px;width:auto;max-width:80%" :widthContent="80"/> -->
<!--            <p style="line-height: 15px;">{{recordData.name}}</p>-->
<!--            <p style="line-height: 15px;">{{sourceVersion.sourceVersionName}}</p>-->
          <!-- </div> -->
        <!-- </a-col> -->
      <!-- </a-row> -->
      <!-- <div style="padding-bottom: 30px" v-if="sourceVersion.checked"> -->
        <!-- <a-row>
          <a-button type="link" style="font-size: 14px;padding-left: 0"
                    @click="sourceVersion.collapse=!sourceVersion.collapse">
            <span v-if="sourceVersion.collapse">+展开</span>
            <span v-else>-收起</span>
            配置信息
          </a-button>
        </a-row> -->
        <!-- <transition name="slide-fade">
          <a-form-model
            :ref="'sourceForm-'+sourceVersion.sourceVersionName"
            :model="sourceVersion"
            :rules="rules"
            v-show="!sourceVersion.collapse"
          >
            <a-row>
              <a-col :span="12" style="padding-right: 15px;"> -->
                <!-- 摘要算法 -->
                <!-- <a-form-model-item
                  :label="$t('zysf')"
                  prop="hashAlgorithm"
                >
                  <a-select
                    v-model="sourceVersion.hashAlgorithm"
                    showSearch
                    allow-clear
                    :placeholder="$t('pleaseSelect')"
                    optionFilterProp="children"
                    :filterOption="$commonFun.filterOption"
                    style="width: 100%"
                  >
                    <a-select-option
                      v-for="(key,val,index) in digestAlgorithm"
                      :key="index"
                      :value="parseInt(val,10)"
                    >
                      {{ key }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item> -->
                <!-- 摘要值 -->
                <!-- <a-form-model-item
                  :label="$t('zyz')"
                > -->
                  <!-- 是否手动输入摘要值 -->
                  <!-- <a-checkbox
                    style="float: right;line-height: 20px;margin-top: -20px"
                    :checked="sourceVersion.isManualEntry"
                    @change="sourceVersion.isManualEntry=$event.target.checked">
                    手动输入
                  </a-checkbox> -->
                  <!-- 手动输入 -->
                  <!-- <a-textarea
                    v-if="sourceVersion.isManualEntry"
                    style="width: 100%"
                    v-model="sourceVersion.checksum"
                    placeholder="请填写摘要值"
                    :rows="5"
                  ></a-textarea> -->
                  <!-- 自动填充 md5或者sha256-->
                  <!-- <a-textarea
                    v-else
                    style="width: 100%"
                    disabled
                    :rows="5"
                    v-model="sourceVersion.checksum"
                  ></a-textarea>
                </a-form-model-item>
              </a-col>
              <a-col :span="12"> -->
                <!-- 预计安装时间 -->
                <!-- <a-form-model-item :label="$t('estimatedInstallTime')+'(s)' " prop="installTime">
                  <a-input-number
                    style="width: 100%"
                    v-model="sourceVersion.installTime"
                    :placeholder="$t('pleaseInput')+$t('estimatedInstallTime')"
                  ></a-input-number>
                </a-form-model-item> -->
                <!-- 超时时长 -->
                <!-- <a-form-model-item :label="$t('timeout')+'(s)'" prop="overTime">
                  <a-input-number
                    style="width: 100%"
                    v-model="sourceVersion.overTime"
                    :placeholder="$t('pleaseInput')+$t('timeout')"
                  ></a-input-number>
                </a-form-model-item> -->
                <!-- 文件烧写类型 -->
                <!-- <a-form-model-item :label="$t('file')+$t('sxType')" prop="dllName">
                  <a-select
                    v-model="sourceVersion.dllName"
                    showSearch
                    allow-clear
                    :placeholder="$t('pleaseSelect')+$t('file')+$t('sxType')"
                    optionFilterProp="children"
                    :filterOption="$commonFun.filterOption"
                    style="width: 100%"
                  >
                    <a-select-option
                      v-for="(item,index) in dllNameDictCode"
                      :key="index"
                      :value="item.value"
                      :title="item.name"
                    >{{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item> -->
              <!-- </a-col> -->
            <!-- </a-row> -->
          <!-- </a-form-model> -->
        <!-- </transition> -->
      <!-- </div> -->
    <!-- </template> -->


    <upload-upgrade-package
      ref="uploadModel"
      :recordData="uploadModalRecordData"
      :newFileType="'1'"
      @refreshData="()=> {updateVersionInfo();$emit('refreshData')}"
      @refreshSoftVersion="$emit('refreshSoftVersion')"
    ></upload-upgrade-package>
    <form-model
      ref="createEcuModal"
      formTitle="原始版本 ECU版本创建【测试版】"
      :width="1208"
      @ok="saveEcuVersion"
      :bodyStyle="{ height: '500px', overflowY: 'auto' }"
    >
      <new-edit-version  ref="ecuVersionForm" :fixedEcu="{ecuModuleId:recordData.ecu.ecuModuleId,modelCode:recordData.modelCode,}" :showModelCode="true"/>
      <!--      TODO close  : add new version-->
    </form-model>

  </form-model>

</template>
<script>
  import FormModel from '@/components/SelfModal/FormModel'
  import ChunkUpload from '@/components/Upload/ChunkUpload'
  import {typeList} from './config'
  import {mapState} from 'vuex'
  import QuestionMarkTip from '@/views/components/QuestionMarkTip'
  import {checkIsRangeInteger} from '@/utils/validate'
  import UploadUpgradePackage from './UploadUpgradePackage.vue'
  import TableEllipsis from '@/components/Ellipsis/TableEllipsis'
  import { softwarePerms } from '@/config/permission/index'
  import AuthText from '@/components/AuthText'
  import { TargetVersionColums, RawVersionColums } from './config'
  import CustomModal from '@/components/CustomModal/index.vue'
  export default {
    name: 'OnlineMakePackage',
    components: {CustomModal,FormModel, ChunkUpload, QuestionMarkTip, UploadUpgradePackage,TableEllipsis,AuthText,
      //循环引用，通过import异步引用
      NewEditVersion : () => import('./NewEditVersion.vue')
      },
    props: {
      //   当前版本信息
      recordData: {
        type: Object,
        default: () => {
          return {}
        }
      },
    },
    computed: {
      ...mapState({
        // 摘要算法
        digestAlgorithm: (state) => state.dict.digestAlgorithm,
        dllNameDictCode: (state) => state.dict.dllNameDictCode,
        dllClassNameDictCode: (state) => state.dict.dllClassNameDictCode,
      })
    },
    data() {
      return {
        isPrevent: false,
        loadingTbData: false,
        // 目标版本数据
        TargetVersionLists: [],
        //列表数据
        tableData: [],
        //选中行数据
        selectedRows: [],
        selectedRowKeys: [],
        TargetVersionColums,
        RawVersionColums,
        targetVersion: null,
        targetEntirePackageCheck: true,//目标版本全包检查标红
        uploadModalRecordData: {},
        sourceVersionList: [],
        form: {
          dllName: '',
          installTime: '',
          overTime: ''
        },
        rules: {
          hashAlgorithm: [{required: true, message: this.$t('pleaseInput')}],
          // lxhmodifyxccode
          installTime: [{
            required: true,
            message: this.$t('pleaseInput')
          }, {validator: checkIsRangeInteger(1, 2147483647)}],
          // lxhmodifyxccode
          overTime: [{
            required: true,
            message: this.$t('pleaseInput')
          }, {validator: checkIsRangeInteger(1, 2147483647)}],
          dllName: [{required: true, message: this.$t('pleaseSelect')}]
        },
        typeList,
        softwarePerms,
        onGetCheckboxProps: (record) => {
        return {
          props: {
            disabled: !record.resourceName
          }
        }
       }
      }
    },
    mounted() {
      this.$store.dispatch('getVersionTypeDictCodeData')
      this.$store.dispatch('getDllClassNameDictCodeData')
    },
    methods: {
      /**
       * data: {resourceId:资源ID，name: 资源名称}
       * @param data
       */
      updateVersionInfoCallback(data) {
        if (this.uploadModalRecordData.id === this.recordData.id) {
          //目标版本上传全包
          this.targetVersion = data;
          this.targetEntirePackageCheck = true;
          this.$emit('refreshVersion');
        } else{
          this.uploadModalRecordData.resourceName = data ? data.name : '';
          this.uploadModalRecordData.resourceId = data ? data.resourceId : '';
        }
      },
      // 上传全包
      uploadEntirePackage(versionInfo) {
        if(versionInfo.sourceVersionName) {
          versionInfo.name = versionInfo.sourceVersionName;
        }
        this.uploadModalRecordData = versionInfo;
        if (!versionInfo.id) {
          this.uploadModalRecordData.id = versionInfo.sourceVersionId;
        }
        // this.uploadModalRecordData = Object.assign({}, versionInfo);
        this.uploadModalRecordData.callback = this.updateVersionInfoCallback;
        this.$refs.uploadModel.handleAdd({resourceType: '10'});
      },
      // 更新(目标/原始)版本信息，上传全包后
      updateVersionInfo() {
        this.loadingTbData = true
        //展示全包资源信息
        this.$api.getResourceList({
          pageNo: 1,
          pageSize: 10,
          targetVersionId: this.uploadModalRecordData.id,
          resourceType: 10 //全包
        }).then(res => {
          if (!res.data || res.data.length === 0) {
            return;
          }
          if (res.data.length > 1) {
            this.$message.error('当前版本存在多个全包！')
            return;
          }
          this.uploadModalRecordData.callback({
            resourceId: res.data[0].id,
            name : res.data[0].name
          });
          this.TargetVersionLists = res.data
          this.form.dllName = this.TargetVersionLists[0].dllName
          this.loadingTbData = false
        })
        .finally(() => {
          this.loadingTbData = false
        })
        //展示版本的materialFile（不使用此种方式：上传后需要异步等待处理成功，方可制作查分）
        // this.$api.versionInfor({
        //   id: this.uploadModalRecordData.id,
        // }).then(res => {
        //   if (!res.data) {
        //     return;
        //   }
        //   this.uploadModalRecordData.callback(res.data.materialFile ? {
        //     name : res.data.materialFile.name
        //   } : null);
        // })
      },
      getSourceList() {
        this.$api.getEcuVersionBefore({
          targetVersionId: this.recordData.id,
          // softwareCode: this.recordData.softwareCode,
          versionType: 1 //配置文件2 零件版本的升级包1
        }).then((res) => {
          var data = res.data;
          let newVersion = data.filter((item) => {
            return this.sourceVersionList.filter((s) => {
              return s.sourceVersionName === item.sourceVersionName;
            }).length === 0;
          });
          newVersion.forEach((item) => {
            item.hashAlgorithm = 1;//MD5
            item.checked = false;
            // item.checked = !!item.name;
            item.collapse = false;
            item.isManualEntry = false;
            !!item.resourceId || (item.resourceId='');
            !!item.resourceName || (item.resourceName='');
          })
          // this.sourceVersionList = Object.assign([], this.sourceVersionList, data);
          this.sourceVersionList = [...newVersion, ...this.sourceVersionList];
        })

      },
      handleAdd() {
        var initData = {
          sourceVersionId: '',
          installTime: 9000,
          overTime: 9000,
          dllName: undefined
        }
        initData.sourceVersionId = []
        this.form = {...initData}
        this.targetEntirePackageCheck = true;
        this.$refs.makeModal.add()
        this.uploadModalRecordData = Object.assign({
          callback: this.updateVersionInfoCallback
        }, this.recordData);
        this.$nextTick(() => {
          this.sourceVersionList = [];
          this.targetVersion = null;
          this.updateVersionInfo();
        })
      },
      saveEcuVersion() {
        this.$refs.ecuVersionForm.getFormData().then((formData) => {
          const params = this.$commonFun.deepCopy(formData)
          params.apiStr = undefined
          var vm = this;
          return new Promise((resolve, reject) => {
            vm.$api[formData.apiStr](params).then(res => {
              //增加一个原始版本
              vm.$message.success(vm.$t('1045'))
              vm.$refs.createEcuModal.visible = false
              vm.$emit('refreshSoftVersion')
              vm.refreshData()
              resolve(res)
            }).catch(err => {
              reject(err)
            }).finally(() => {
              vm.$refs.makeModal.confirmLoading = false
            })
          })
        });

      },
      handleOk() {
        if (this.selectedRowKeys.length === 0) {
          this.$message.error("请选择原始版本！");
          return;
        }
        if (this.isPrevent) {
          return
        }
        this.isPrevent = true
        const resourceItemDtoList = []
        this.selectedRows.forEach((item) => {
          resourceItemDtoList.push({
            dllName: this.form.dllName,
            installTime: this.form.installTime,
            overTime: this.form.overTime,
            sourceVersionId: item.sourceVersionId,
            sourceVersionName: item.sourceVersionName,
            versionPhase: item.versionPhase,
            resourceId: item.resourceId,
            resourceName: item.resourceName,
            hashAlgorithm: 1
          })
        })
        const data = {
          materialFileType: 2,
          targetVersionId: this.TargetVersionLists[0].targetVersionId,
          resourceItemDtoList
        }
        this.$api.diffResourceSaveBatch(data).then(() => {
            this.isPrevent = false
            this.$refs.makeModal.visible = false
            this.$emit('refreshData')
          }).finally(() => {
            this.isPrevent = false
            this.$refs.makeModal.confirmLoading = false
          })
      },
      // 在线制作方式保存
      saveDiffResource() {
        return new Promise((resolve, reject) => {
          var data = Array.from(this.sourceVersionList.filter(item => item.checked), item => {
            var t = {...item};
            delete t.checked;
            delete t.collapse;
            delete t.isManualEntry;
            return t;
          });

          var param = {
            materialFileType: 2,
            resourceItemDtoList: data,
            targetVersionId: this.recordData.id,
          }
          // encryptType: vm.recordData.ecu ? vm.recordData.ecu.encryptType : '' // 零件的加密方式
          this.$api.diffResourceSaveBatch(param).then(() => {
            resolve()
          })
        })
      },
      deleteEntirePackage (id, callback) {
        const vm = this
        this.$confirm({
          title: vm.$t('delete'),
          content: "您确定要删除吗？",
          class: 'confirmStyle',
          icon: '<Icon >',
          width: 378,
          onOk () {
            vm.$api.deleteResource({ ids: [id] }).then(response => {
              vm.$message.success(vm.$t('successfullyDelete'))
              // vm.refreshData() // 刷新页面
              vm.$emit('refreshData')
              if (callback) {
                callback();
              }
            })
          },
          onCancel () { }
        })
      },
    loadData (parameter) {
      const vm = this
      this.tableData = []
      this.selectedRows = []
      this.selectedRowKeys = []
      const apiPromise = vm.$api.getEcuVersionBefore({ ...parameter, targetVersionId: this.recordData.id, versionType: 1 })
      return new Promise((resolve, reject) => {
        return apiPromise.then((res) => {
          if (res.data) {
            this.tableData = res.data
          }
          resolve(res)
        }).catch((err) => {
          reject(err)
        })
      })
    },
    refreshData (isToFirstPage = true) {
      const vm = this
      vm.$nextTick(() => {
        vm.$refs.table.refresh(isToFirstPage)
      })
    },
    onTableSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    }
  }
}
</script>
<style lang="less">
  .slide-fade-enter-active {
    transition: all .6s ease;
  }

  .slide-fade-leave-active {
    transition: all .3s ease;
    /*transition: all .3s cubic-bezier(1.0, 0.5, 0.8, 1.0);*/
  }

  .slide-fade-enter, .slide-fade-leave-to
    /* .slide-fade-leave-active for below version 2.1.8 */ {
    transform: translateY(30px);
    opacity: 0;
  }

  .has-error {
    color: red;

    button.ant-btn {
      border-color: red;
    }
  }

  .makePackageStyle {
    .ant-form-item .ant-form-item-label span {
      font-size: 15px;
    }

    .ant-row {
      .ant-btn {
        height: 26px;

        i {
          font-size: 13px;
        }
      }
    }

  }

</style>
<style lang="less" scoped>
  ::v-deep .rightDrawerWithoutCol {
    overflow: visible !important;
  }
</style>
